import Vue, { DirectiveOptions } from 'vue'
import App from './App.vue'
import router from '@/router'
import store from './store'
// 标准html5浏览器默认样式，比如body-margin:0,原始浏览器margin:8px 等等
import 'normalize.css'
// import './registerServiceWorker';
import '@/styles/element-variables.scss'
import ElementUI from 'element-ui'
import '@/styles/new-element.scss'
import '@/styles/index.scss'
import { AppModule } from '@/store/modules/app'

import * as directives from '@/directives'
import * as filters from '@/filters'

import settings from './settings'
import SvgIcon from 'vue-svgicon'
import '@/icons/components'
import { UserModule } from '@/store/modules/user'
import { PermissionModule } from '@/store/modules/permission'
import { Message } from 'element-ui'
import { get } from 'lodash'

import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
console.log('registerMicro', UserModule)
Vue.config.devtools = process.env.NODE_ENV === 'development'

Vue.use(codemirror)

Vue.config.productionTip = false

Vue.use(ElementUI, {
  size: AppModule.size // Set element-ui default size
})
// 统一设置svg-icon风格
Vue.use(SvgIcon, {
  tagName: 'svg-icon',
  defaultWidth: '1em',
  defaultHeight: '1em'
})
// 动态加载路由
getPermissionRoutes()
// 只渲染一次菜单树

async function getPermissionRoutes() {
  if (UserModule.token) {
    UserModule.setMenuRending(true)
    await UserModule.GetMenu().catch(err => {
      console.log('这里报错了')
      console.error(err)
      UserModule.ResetToken()
      Message.error({ message: err || 'Has Error' })
      setTimeout(() => {
        // location.reload()
        console.log('wuyu')
      }, 0)
    })
    await UserModule.GetUserInfo()
    const menuTree = UserModule.menuTree
    if (menuTree.length > 0) {
      // Generate accessible routes map based on role
      PermissionModule.GenerateRoutes({ menuTree: menuTree })

      // tips 放到最后加载404会避免页面刷新时，路由加载无效的问题
      // 先一次性加载所有二级路由
      console.log(PermissionModule.dynamicRoutes)
      router.addRoutes(PermissionModule.dynamicRoutes)
    } else {
      // 没有路由的时候
      router.addRoutes([
        {
          path: '/index',
          redirect: '/401',
          meta: { hidden: true }
        },
        {
          path: '/401',
          component: () => import('@/views/error-page/401.vue'),
          meta: { hidden: true }
        }
      ])
    }
    setTimeout(() => {
      UserModule.setMenuRending(false)
    }, 300)
  }
}

import '@/permission'
Vue.prototype.settings = settings
Vue.prototype.$_get = get
// Register global directives
Object.keys(directives).forEach(key => {
  Vue.directive(key, (directives as { [key: string]: DirectiveOptions })[key])
})
// Register global filter functions
Object.keys(filters).forEach(key => {
  Vue.filter(key, (filters as { [key: string]: Function })[key])
})
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
